package app.controllers;

import app.Const;
import app.constant.TransferConstant;
import app.kit.TypeKit;
import app.models.basic.Dict;
import app.models.basic.Notes;
import app.models.member.Member;
import app.models.order.Order;
import app.models.product.Details;
import app.models.product.Product;
import app.models.transfer.TransferProduct;
import app.services.OrderService;
import bank.BankService;
import com.google.common.base.Optional;
import com.google.common.base.Strings;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.jfinal.aop.Before;
import com.jfinal.ext.interceptor.GET;
import com.jfinal.plugin.activerecord.Page;
import goja.GojaConfig;
import goja.StringPool;
import goja.mvc.AjaxMessage;
import goja.mvc.Controller;
import goja.rapid.db.RequestParam;
import goja.security.goja.SecurityKit;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.joda.time.Days;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static app.Const.FIELD_CODE;
import static app.Const.FIELD_COLLECTION_MODE;
import static app.Const.FIELD_NAME;
import static app.Const.FIELD_PRICE;
import static app.Const.FIELD_PRODUCT;
import static app.Const.FIELD_RISK_TOLERANCE;
import static app.Const.FIELD_TIME_LIMIT_UNIT;
import static app.Const.FIELD_YIELD;
import static app.Const.PARAM_PAGE;
import static app.Const.PARAM_PAGESIZE;
import static goja.StringPool.EMPTY;

/**
 * <p>
 * The url transfer Controller.
 * </p>
 *
 * @author sagyf yang
 * @version 1.0
 * @since JDK 1.6
 */
public class TransferController extends Controller {

    private static final List<String> order_fields = Lists.newArrayList(FIELD_YIELD, "remaining_days", FIELD_PRICE);

    /**
     * The index route.
     * the url /transfer
     * the view in index.ftl
     * <p/>
     * {sort}?page=1&pageSize=12
     * page       页码
     * sort  排序字段 field_dir like  yield_asc
     * pageSize   每页显示数量
     */
    @Before(GET.class)
    public void index() {
        setAttr("curent", 4);
        // 取得 昨日的交易总量

        TransferProduct yesterdayCount = TransferProduct.dao.findByYesterdayCount();
        setAttr("yesterday", yesterdayCount);

        // 取得历史累计交易
        TransferProduct allCount = TransferProduct.dao.findByAllCount();
        setAttr("all", allCount);

        int page = getParaToInt(PARAM_PAGE, 1);
        int pageSize = getParaToInt(PARAM_PAGESIZE, 12);
        String sort = getPara(0, EMPTY);
        String sort_field = EMPTY;
        RequestParam.Direction sort_direction = null;
        if (!Strings.isNullOrEmpty(sort)) {
            final int sort_index = sort.lastIndexOf("_");
            sort_field = sort.substring(0, sort_index);
            String sort_dir = sort.substring(sort_index + 1);
            if (order_fields.contains(sort_field)) {
                if (StringUtils.equals("asc", sort_dir)) {
                    sort_direction = RequestParam.Direction.ASC;
                } else if (StringUtils.equals("desc", sort_dir)) {
                    sort_direction = RequestParam.Direction.DESC;
                } else {
                    sort_direction = RequestParam.Direction.ASC;
                }
            } else {
                sort_field = EMPTY;
            }
        }
        Page<TransferProduct> results = TransferProduct.dao.findByPageList(page, pageSize, sort_field, sort_direction);
        setAttr("data", results);
        setAttr("sort_field", sort_field);

        if (sort_direction != null) {
            setAttr("sort_dir", sort_direction == RequestParam.Direction.DESC ? "asc" : "desc");
        }

        render("../transfer.ftl");
    }


    public void info(){
        setAttr("curent", 4);
        int transferId = getParaToInt(0,0);
        if(transferId  > 0){
            TransferProduct transferProduct = TransferProduct.dao.findByAllInfo(transferId);
            if (transferProduct == null) {
                renderError(404);
                return;
            }

            setAttr(FIELD_TIME_LIMIT_UNIT, Dict.getTimeLimit(transferProduct.getStr(FIELD_TIME_LIMIT_UNIT)));
            setAttr("coll_mode", Dict.dao.collection_mode_map(TypeKit.getInt(transferProduct, FIELD_COLLECTION_MODE)));
            DateTime valuedate = new DateTime(transferProduct.getTimestamp("valuedate").getTime());
            DateTime dueDate = new DateTime(transferProduct.getTimestamp("due_time").getTime());
//            DateTime now = DateTime.now();
            final int days = Days.daysBetween(valuedate, dueDate).getDays();
//            if(days > 0){
//
//                final int todays = Days.daysBetween(now, dueDate).getDays();
//                double progress = ArithKit.div(todays, days, 2) * 100;
//                if(progress > 100){
//                    progress = 100;
//                }
//                setAttr("date_progress", progress);
//            }
            setAttr("days", days+1);
            int productid = TypeKit.getInt(transferProduct, Const.FIELD_PRODUCT);

            Product product = Product.dao.findByWebIntro(productid);
            setAttr(Const.FIELD_PRODUCT, product);


            setAttr("risk_txt", Notes.dao.findByRisk());
            setAttr("buy_txt", Notes.dao.findByBuy());

            Details riskByProduct = Details.dao.findRiskByProduct(productid);
            setAttr("details", riskByProduct!=null?riskByProduct.getStr("attribute_val"): StringPool.EMPTY);
            BigDecimal prifit = transferProduct.profit();
            setAttr("prifit",prifit);
            setAttr("transferproductjson", transferProduct.toJson());

            // 产品描述

            List<Details> productDetailses = Details.dao.findByWebItem(productid);

            setAttr("intros", productDetailses);

            setAttr("jump_url", GojaConfig.getProperty("bank.epcs.url"));
            setAttr("p", transferProduct);
            //产品转让协议
            setAttr("transfer_notes", Notes.dao.findByTransfer());
        }
    }


    /**
     * 立即投资
     */
    public void investment() {
        setAttr("curent", 2);
        int transferProductId = getParaToInt(0, 0);
        if (transferProductId > 0) {

//            String orderId = getPara("order");

            if (!SecurityKit.isLogin(getRequest())) {
                renderAjaxNologin();
                return;
            }

            final Member member = SecurityKit.getLoginUser(getRequest());

            if (Strings.isNullOrEmpty(member.getStr("electronic_account"))) {
                renderJson(AjaxMessage.failure("请先绑定电子账户后在进行投资", "ELE", null));
                return;
            }

            TransferProduct transferProduct = TransferProduct.dao.findByAllInfo(transferProductId);
            if (transferProduct == null) {
                renderAjaxFailure("请选择购买投资产品");
                return;
            }
            int status = TypeKit.getStatus(transferProduct);
            switch (status){
                case TransferConstant.STATUE_CANCEL:
                    renderAjaxFailure("十分抱歉，转让人已撤销该产品的转让。");
                    return;
                case TransferConstant.STATUE_SUCCESS:
                    renderAjaxFailure("十分抱歉，该产品已被其他人购买，转让成功了！");
                    return;
                case TransferConstant.STATUE_FAIL:
                    renderAjaxFailure("十分抱歉，该产品已被下架无法进行购买！");
                    return;
            }

            if (member.getId() == TypeKit.getInt(transferProduct, "assignor")) {
                renderAjaxFailure("无法购买自己转让的产品!");
                return;
            }


            final Map<String, Object> results = Maps.newHashMap();

            Order order = OrderService.me.createTfrOrder(member.getId(), transferProduct);

            // 剩余天数
            int remaining_days = TypeKit.getInt(transferProduct, "remaining_days");
            // 计算 起息和到息
            DateTime now = DateTime.now();
            final Date begin_interest = now.toDate();
            results.put("begin_interest", begin_interest);
            now = now.plusDays(remaining_days);
            final Date end_interest = now.toDate();
            results.put("end_interest", end_interest);

            final String risk_tolerance = Dict.dao.collection_mode_map(TypeKit.getInt(transferProduct, FIELD_RISK_TOLERANCE));
            results.put(FIELD_RISK_TOLERANCE, risk_tolerance);

            results.put(FIELD_PRODUCT, transferProduct);

            final String productName = transferProduct.getStr(FIELD_NAME);
            final String memberCode = member.getStr(FIELD_CODE);
            final String orderCode = order.getStr("trade_no");
            final Optional<Map<String, String>> oks = BankService.me.nopwdCreateOrderSign(now, now, memberCode, orderCode,
                    "转让购买 [" + productName + "] 产品", "购买转让产品 [" + productName + "]，融理财富平台",
                    String.valueOf(TypeKit.getDouble(transferProduct, FIELD_PRICE)),
                    GojaConfig.domain() + "pay/tip", GojaConfig.domain() + "pay/asyn");
            if (oks.isPresent()) {
                results.put("pay", oks.get());
            } else {
                renderAjaxFailure("系统发生错误，请稍后再试");
                return;
            }

            results.put("order", order);

            renderAjaxSuccess(results);

        } else {
            renderAjaxFailure();
        }
    }
}